<template>
	<view>
		<view @click="onOpenWifi" class="wifi l-f l-row-sb">
			<view class="l-f">
				<view>
					<image 
					v-if="!isConnect"
					class="wifi_icon" 
					src="@/static/images/wifi_no_connect.png" 
					mode="widthFix"></image>
					<view class="wifi_connect l-f l-row-c" v-else>
						<image class="wifi_connect_icon" src="@/static/images/wifi.png" mode="widthFix"></image>
					</view>
				</view>
				<view class="wifi_info">
					<view class="wifi_info_label" v-if="!isConnect">暂未连接wifi</view>
					<view class="wifi_info_label" v-else>{{connectWifiInfo.SSID}}</view>
					<view class="wifi_info_number l-line1" v-if="isConnect">设备编号：{{connectWifiInfo.SSID}}</view>
				</view>
			</view>
			<view 
			v-if="!isConnect"
			class="wifi_btn" 
			hover-class="hover-class">连接</view>
			<view 
			v-else
			@click.stop="onCloseWifi"
			class="wifi_close"
			hover-class="hover-scale"
			:hover-stay-time="100">
				<image class="wifi_close_icon" src="@/static/images/wifi_close.png" mode="widthFix"></image>
			</view>
		</view>
		<!-- wifi-connect -->
		<wifi-connect ref="wifiConnect" @submit="onConnectSubmit" />
		<!-- wifi-list -->
		<wifi-list ref="wifiList" 
		:list="wifiList" 
		:connect="connectWifiInfo"
		@connect="onConnect" 
		@del="onDelConnect"
		@edit="onEditConnect"
		 />
	</view>
</template>

<script>
	import WifiConnect from '@/components/wifi-connect/wifi-connect.vue'
	import WifiList from '@/components/wifi-list/wifi-list.vue'
	import {mapState} from 'vuex'
	export default {
		name:"wifi",
		components: {
			WifiConnect,
			WifiList
		},
		computed: {
			...mapState(['isConnect','connectWifiInfo'])
		},
		data() {
			return {
				connectWifiList: [], // 当前本地连接过的wifi列表
				wifiList: [], // 当前搜索的wifi列表
				password: '',
				isOpen: false,
				currentConnect: {}
			};
		},
		mounted() {
			this.initWifi()
		},
		methods: {
			// 打开连接wifi
			onOpenWifi() {
				this.$refs.wifiList.open()
			},
			// 初始化wifi
			initWifi() {
				// 获取本地存储wifi
				let connectWifiList = uni.getStorageSync('connectWifiList') | []
				if(connectWifiList) {
					this.connectWifiList = connectWifiList
				}
				console.log(this.connectWifiList)
				uni.startWifi({
					success: e => {
						this.isOpen = true
						// 获取wifi信息
						uni.getConnectedWifi({
							success: result => {
								this.onConnectSuccess(result)
							}
						})
						uni.getWifiList({
							success: res => {
								console.log('获取wifi列表成功')
							},
							fail: err => {
								console.log(err)
							}
						})
					}
				})
				// 监听wifi列表
				uni.onGetWifiList((e) => {
					let list = e.wifiList,
						newList = []
					// 过滤一些没用的
					for (let i = 0; i < list.length; i++) {
						if(list[i].SSID) {
							newList.push(list[i]) 
						}
					}
					// 判断是否为连接过的wifi
					for (let i = 0; i < this.connectWifiList.length; i++) {
						for (let j = 0; j < newList.length; j++) {
							if(this.connectWifiList[i].BSSID === newList[j].BSSID) {
								newList[j].isExist = true
							}else {
								newList[j].isExist = false
							}
						}
					}
					// 排序
					newList.sort(this.compare)
					this.wifiList = newList
				})
				let password = uni.getStorageSync('password') || ''
				let connectWifiInfo = uni.getStorageSync('wifi') || {}
				if(password && JSON.stringify(connectWifiInfo) !== '{}') {
					this.password = password
					this.onConnectWifi(connectWifiInfo.SSID,connectWifiInfo.BSSID,password)
				}
			},
			// 打开连接wifi
			onOpenWifi() {
				this.$refs.wifiList.open()
			},
			// 连接wifi
			onConnect(item) {
				this.currentConnect = item
				this.$refs.wifiConnect.open()
			},
			onConnectSubmit(password = '') {
				const {SSID = '',BSSID = ''}  = this.currentConnect
				this.onConnectWifi(SSID,BSSID,password)
			},
			// 连接成功事件
			onConnectSuccess(e) {
				if(this.isConnect) return
				try{
					if(e.wifi.frequency === -1) {
						uni.showToast({
							title: '密码错误,连接失败！',
							icon: 'none',
							position: 'top'
						})
						return
					}
					this.$store.commit('SET_CONNECT_INFO',e.wifi)
					this.$store.commit('SET_CONNECT',true)
					uni.showToast({
						title: '连接成功!',
						icon: 'none',
						position: 'top',
						duration: 2000
					})
					this.setStorageWifi({
						...this.connectWifiInfo,
						password:this.password
					})
					this.$refs.wifiConnect.close()
					this.$refs.wifiList.close()
					uni.setStorageSync('password',this.password)
					uni.setStorageSync('wifi',this.connectWifiInfo)
				}catch(e){
					//TODO handle the exception
				}
			},
			// 连接
			onConnectWifi(SSID,BSSID,password) {
				if(!this.isOpen) {
					uni.startWifi()
				}
				uni.showLoading({
					title: '连接中...'
				})
				this.password = password
				uni.connectWifi({
					SSID: SSID,
					BSSID: BSSID,
					password: password,
					maunal: false,
					partialInfo: true,
					success: (e) => {
						console.log('wifi连接正常')
						console.log(e)
						setTimeout(()=> {
							uni.getConnectedWifi({
								success: result => {
									console.log(result)
									this.onConnectSuccess(result)
								}
							})
						},1000)
					},
					fail: err => {
						console.log(err)
						if(err.errCode === 12001) {
							uni.showToast({
								title: '当前wifi不支持连接',
								icon: 'none',
								position: 'top'
							})
						}
						if(err.errCode === 12002) {
							uni.showToast({
								title: '密码错误',
								icon: 'none',
								position: 'top'
							})
						}
						if(err.errCode === 12005) {
							uni.showToast({
								title: '请先打开wifi',
								icon: 'none',
								position: 'top'
							})
						}
					},
					complete: ()=> {
						uni.hideLoading()
					}
				})
			},
			// 删除连接
			onDelConnect(item) {
				this.setStorageWifi(item,true)
			},
			// 修改连接密码
			onEditConnect(item) {
				this.currentConnect = item
				this.$refs.wifiList.close()
				this.$refs.wifiConnect.open()
			},
			// 关闭wifi连接
			onCloseWifi() {
				uni.showModal({
					title: '关闭提示',
					content: '确定关闭当前连接?',
					success: (e) => {
						if(e.confirm) {
							uni.stopWifi({
								success: e => {
									this.isOpen = false
									this.$store.commit('SET_CONNECT',false)
									this.$store.commit('SET_CONNECT_INFO',{})
									uni.showToast({
										title: '已关闭连接!',
										icon: 'none',
										position: 'top'
										
									})
								}
							})
						}
					}
				})
			},
			// 存储连接过的wifi
			setStorageWifi(item,isDel = false) {
				// 判断是否存在过
				if(this.connectWifiList.length === 0) {
					this.connectWifiList.push(item)
				}else {
					for (let i = 0; i < this.connectWifiList.length; i++) {
						if(isDel) {
							this.connectWifiList.splice(i,1)
							this.$store.commit('SET_CONNECT',false)
							this.$store.commit('SET_CONNECT_INFO',{})
							break;
						}else {
							if(this.connectWifiList[i].BSSID === item.BSSID) {
								// 更新
								this.$set(this.connectWifiList,i,item)
								break;
							}else {
								this.connectWifiList.push(item)
								break;
							}
						}
					}
				}
				uni.setStorageSync('connectWifiList',this.connectWifiList)
			},
			//比较函数
			compare(x, y) {
				if (Math.abs(x.signalStrength) < Math.abs(y.signalStrength)) {
					return -1;
				} else if (Math.abs(x.signalStrength) > Math.abs(y.signalStrength)) {
					return 1;
				} else {
					return 0;
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
.wifi {
	height: 176rpx;
	border-radius: 76rpx;
	padding: 0 32rpx;
	box-sizing: border-box;
	background: linear-gradient(to bottom,rgba(26, 27, 30, 1),rgba(53, 54, 56, 1));
	&_icon {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
	}
	&_connect {
		background: url("@/static/images/wifi_bg.png") no-repeat;
		background-size: 100%;
		width: 100rpx;
		height: 100rpx;
		&_icon {
			width: 42rpx;
			height: 42rpx;
		}
	}
	&_info {
		margin-left: 30rpx;
		&_label {
			font-size: 30rpx;
			color: #ffffff;
			font-weight: 700;
		}
		&_number {
			font-size: 24rpx;
			color: rgba(136, 136, 136, 1);
			margin-top: 16rpx;
		}
	}
	&_btn {
		font-size: 20rpx;
		color: #ffffff;
		width: 115rpx;
		height: 72rpx;
		border-radius: 96rpx;
		text-align: center;
		line-height: 70rpx;
		background: linear-gradient(to bottom,rgba(72, 228, 239, 1),rgba(43, 206, 181, 1));
	}
	&_close {
		&_icon {
			width: 176rpx;
			height: 176rpx;
		}
	}
}
</style>